package com.pkk.penguin.frame.know.boot.view.controller.zysynch;

import static com.pkk.penguin.frame.know.boot.config.handle.zhiyi.synch.ZySynchContent.AUTH_PLATEFORM_SET;
import static com.pkk.penguin.frame.know.boot.config.handle.zhiyi.synch.ZySynchContent.AUTH_USER_SET;
import static com.pkk.penguin.frame.know.boot.config.handle.zhiyi.synch.ZySynchContent.USER_AUTH_INFO;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pkk.components.rpc.request.CommonRequest;
import com.pkk.components.rpc.response.CommonResponse;
import com.pkk.components.rpc.response.util.ResponseUtil;
import com.pkk.penguin.frame.know.boot.apis.zhiyi.SynchApi;
import com.pkk.penguin.frame.know.boot.config.common.handle.AbstractWebSocketServer;
import com.pkk.penguin.frame.know.boot.config.common.handle.AbstractWebSocketServer.WebScoketUtil;
import com.pkk.penguin.frame.know.boot.config.handle.zhiyi.synch.ZySynchContent;
import com.pkk.penguin.frame.know.boot.config.handle.zhiyi.synch.ZySynchWebSocketServer;
import com.pkk.penguin.frame.know.boot.constand.ConfigConstand.RequestType;
import com.pkk.penguin.frame.know.boot.view.controller.common.AbstractAppletController;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description: 之易同步服务控制器
 * @author: peikunkun
 * @create: 2020-05-20 10:01
 **/
@Slf4j
@RestController
@RequestMapping("zySynch")
public class ZySynchAppletController extends AbstractAppletController {

  @Resource
  private ZySynchWebSocketServer zySynchWebSocketServer;
  @Resource
  private ZySynchContent zySynchContent;


  /**
   * @Description: 用户登录
   * @Param: request
   * @return: com.pkk.components.rpc.response.CommonResponse<java.lang.Boolean>
   * @Author: peikunkun
   * @Date: 2020/6/1 0001 上午 11:17
   */
  @RequestMapping("userLogin")
  public CommonResponse<String> userLogin(@RequestBody CommonRequest<JSONObject> request) {
    final JSONObject body = request.getBody();
    final String username = body.getString("username");
    final String password = body.getString("password");
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
      return ResponseUtil.error("请输入账号或者密码");
    }
    zySynchContent.handleZhiYiAuth(username, password);
    return ResponseUtil.success("处理鉴权成功");
  }


  /**
   * @Title: updateConfig<br>
   * @Description: <更新操作失败><br>
   * @author peikunkun<br>
   * @date 2020/5/20 0020 下午 9:02<br>
   * @URL:[]
   * @version V1.0<br>
   */

  @RequestMapping("urlOperate")
  public CommonResponse<Boolean> urlOperate(@RequestBody CommonRequest<JSONObject> request) {
    final JSONObject body = request.getBody();
    String url = body.getString("url");
    final String param = body.getString("param");
    final String username = body.getString("username");
    final String type = body.getString("type");
    final JSONArray execPlatforms = body.getJSONArray("platforms");

    log.info("[同步之易数据]-{}", body);
    if (StringUtils.isBlank(url) || StringUtils.isBlank(type) || StringUtils.isBlank(param)) {
      WebScoketUtil.broadcostOperate(zySynchWebSocketServer.getWebSocket(), url + "参数缺失\n");
      return ResponseUtil.success(false);
    }

    final ConcurrentHashMap<String, SynchApi> authInfo = USER_AUTH_INFO.get(username);
    if (!AUTH_USER_SET.contains(username) || null == authInfo) {
      WebScoketUtil.broadcostOperate(zySynchWebSocketServer.getWebSocket(), "用户未登录:[" + username + "]\n");
      return ResponseUtil.error("用户未登录");
    }

    //去掉不必要的字符
    url = url.startsWith("/") ? url.replaceFirst("/", "") : url;
    String finalUrl = url;
    StringBuffer log = new StringBuffer("------------------------------------\n");
    if (execPlatforms.size() == 0) {
      log.append("请选择要执行的平台");
    } else {
      execPlatforms.stream().forEach(pl -> {
        final String platform = pl.toString();
        final SynchApi synchApi = authInfo.get(platform);
        if (null != synchApi) {
          try {
            final String result = synchApi.connection(finalUrl, RequestType.get(Integer.valueOf(type)), param);
            log.append("[" + platform + "]").append("[" + result + "]\n");
          } catch (Exception e) {
            log.append("[" + platform + "]").append("出现异常[" + e.getMessage() + "]\n");
          }
        }
      });
    }
    log.append("------------------------------------\n\n");
    System.out.println("【更新接口】\n" + log.toString());
    WebScoketUtil.broadcostOperate(zySynchWebSocketServer.getWebSocket(), log.toString());
    return ResponseUtil.success(true);
  }


  /**
   * @Title: updateConfig<br>
   * @Description: <缓存的更新><br>
   * @author peikunkun<br>
   * @date 2020/5/20 0020 下午 9:02<br>
   * @URL:[]
   * @version V1.0<br>
   */
  @RequestMapping("cacheOperate")
  public CommonResponse<Boolean> cacheOperate(@RequestBody CommonRequest<JSONObject> request) {
    final JSONObject body = request.getBody();
    final String command = body.getString("command");
    final String username = body.getString("username");
    final JSONArray execPlatforms = body.getJSONArray("platforms");

    final ConcurrentHashMap<String, SynchApi> authInfo = USER_AUTH_INFO.get(username);
    if (!AUTH_USER_SET.contains(username) || null == authInfo) {
      WebScoketUtil.broadcostOperate(zySynchWebSocketServer.getWebSocket(), "用户未登录:[" + username + "]\n");
      return ResponseUtil.error("用户未登录");
    }

    log.info("[同步之易数据]-{}", body);
    StringBuffer log = new StringBuffer("------------------------------------\n");
    if (StringUtils.isBlank(command) || execPlatforms.size() == 0) {
      return ResponseUtil.success(false);
    } else {
      execPlatforms.stream().forEach(pl -> {
        final String platform = pl.toString();
        final SynchApi synchApi = authInfo.get(platform);
        if (null != synchApi) {
          final String result = synchApi.synchCache(command);
          log.append("[" + platform + "]").append("[" + result + "]\n");
        }
      });
    }
    log.append("------------------------------------\n\n");
    System.out.println("【更新缓存】\n" + log.toString());
    WebScoketUtil.broadcostOperate(zySynchWebSocketServer.getWebSocket(), log.toString());
    return ResponseUtil.success(true);
  }


  /**
   * @Description: 获取webSocketServer
   * @Param:
   * @return: java.util.concurrent.ConcurrentHashMap<java.lang.String, com.pkk.penguin.frame.know.boot.config.common.handle.AbstractWebSocketServer>
   * @Author: peikunkun
   * @Date: 2020/6/1 0001 下午 2:07
   */
  @Override
  protected ConcurrentHashMap<String, AbstractWebSocketServer> getWebSocketServer() {
    return zySynchWebSocketServer.getWebSocket();
  }

  /**
   * @Description: 处理平台列表
   * @return: com.alibaba.fastjson.JSONArray
   * @Author: peikunkun
   * @Date: 2020/6/1 0001 下午 2:04
   */
  @Override
  protected JSONArray handlePlatformList() {
    return JSONArray.parseArray(JSONObject.toJSONString(AUTH_PLATEFORM_SET));
  }
}
